﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxCallback;
using TaskKernel.Configuration;
using TaskKernel.DTO;
using TaskKernel.Domain;
using TaskWebApplicationUI.PresenterLayer;
using File = TaskKernel.Domain.File;

namespace TaskWebApplicationUI
{
    public interface IEditTaskView : ICreateTaskView
    {
        int PercentComplete { set; get; }
        string TaskStatus { set; }
        string DateCreate { set; }
        string TaskOwner { set; }
        string WorkingTime { set; get; }
        string ResultWorkingTime { set; }
        string ExecutorName { set; }
        DateTime? ReminderDate { get; set; }
        bool TaskExecutionInProgress { set; }
        bool SystemMessage { get; }
        IList<HistoryModel> HistoryEntries { set; }
        IList<HistoryModel> FileHistoryEntries { set; }
        int RatingValue { get; set; }
        string RatingText { get; set; }
    }

    public partial class EditTaskView : ViewPage<IEditTaskView, EditTaskPresenter>, IEditTaskView
    {
        private UniversalModelDDL deletedParticipant;
        private IList<File> files = new List<File>();

        public bool SortDirection
        {
            get { return ViewState["sortDirectionASC"] != null ? (bool)ViewState["sortDirectionASC"] : true; }
            set { ViewState["sortDirectionASC"] = value; }
        }

        #region IEditTaskView Members

        public string DepartmentName
        {
            set { Department.Text = value; }
        }

        public IList<File> Filez
        {
            get
            {
                var fileSize = long.Parse(ConfigurationManager.AppSettings["maxFileSize"]);
                for (var i = 0; i < Request.Files.Count; i++)
                {
                    if (String.IsNullOrEmpty(Request.Files[i].FileName)) continue;
                    var stream = Request.Files[i].InputStream;
                    if (stream.Length >= fileSize || stream.Length <= 0) continue;
                    var buffer = Tools.ReadFully(stream);
                    files.Add(new File(Path.GetFileName(Request.Files[i].FileName), buffer, Tools.GetMD5HashCode(buffer)));
                }
                return files;
            }
            set { files = value; }
        }

        public string ReminderNote
        {
            get { return TextReminderTB.Text; }
            set { TextReminderTB.Text = value; }
        }

        public bool ReminderEnable
        {
            set
            {
                ReminderPanel.Visible = value;
                ReminderCB.Checked = value;
            }
            get { return ReminderCB.Checked; }
        }

        public DateTime? ReminderDate
        {
            get { return (DateTime?)dxReminderDate.Value; }
            set { dxReminderDate.Value = value; }
        }

        public string IPAddress
        {
            get { return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }
        }

        public Permissions RolePermissions
        {
            set
            {
                CompleteTextBox.Enabled = value.Complete;
                PrioritiesDDL.Enabled = value.Priority;
                ExecutorsDDL.Enabled = value.Executors;
                dxExpirationDate.Enabled = value.Expiration;
                DepartmentsDDL.Enabled = value.Department;
                BCloseTask.Enabled = value.Close;
                BCloseTask.Visible = value.Close;
                CloseImmediately.Enabled = value.ForceClose;
                CloseImmediately.Visible = value.ForceClose;
                DeleteTaskLB.Visible = value.Delete;
                DeleteTaskLB.Enabled = value.Delete;
                BtnAddComment.Enabled = value.Save;
                BtnAddComment.Visible = value.Save;
                BtnUnClose.Enabled = value.UnClose;
                BtnUnClose.Visible = value.UnClose;
                SystemMessageCheckBox.Enabled = value.System;
                SystemMessageCheckBox.Visible = value.System;
            }
        }

        public string ErrorMessage
        {
            set { ErrorMessageLabel.Text = value; }
            get { return ErrorMessageLabel.Text; }
        }

        public bool SystemMessage
        {
            get { return SystemMessageCheckBox.Checked; }
        }

        public IList<HistoryModel> HistoryEntries
        {
            set
            {
                ViewState["HistoryList"] = value;
                HistoryEntriesGridView.DataSource = value;
                HistoryEntriesGridView.DataBind();
            }
            get { return (IList<HistoryModel>)ViewState["HistoryList"]; }
        }

        public IList<HistoryModel> FileHistoryEntries
        {
            set
            {
                ViewState["FileHistoryList"] = value;
                FileHistoryEntriesGridView.DataSource = value;
                FileHistoryEntriesGridView.DataBind();
            }
            get { return (IList<HistoryModel>)ViewState["FileHistoryList"]; }
        }

        public int RatingValue
        {
            get { return (int)myRating.Value; }
            set { myRating.Value = value; }
        }

        public string RatingText
        {
            get { return mRatingComment.Text; }
            set { lbAllVotes.Text = value; }
        }

        public int PercentComplete
        {
            get { return Int32.Parse(CompleteTextBox.Text); }
            set { CompleteTextBox.Text = value.ToString(); }
        }

        public IList<UniversalModelDDL> Executors
        {
            set
            {
                ExecutorsDDL.DataSource = value;
                ExecutorsDDL.DataBind();
            }
        }

        public IList<UniversalModelDDL> Users
        {
            set
            {
                UsersDDL.DataSource = value;
                UsersDDL.DataTextField = "Name";
                UsersDDL.DataValueField = "ID";
                UsersDDL.DataBind();
            }
        }

        public Guid SelectedUser
        {
            get
            {
                if (UsersDDL.SelectedItem != null)
                    return new Guid(UsersDDL.SelectedItem.Value);
                return Guid.Empty;
            }
        }

        public IList<UniversalModelDDL> Departments
        {
            set
            {
                DepartmentsDDL.DataSource = value;
                DepartmentsDDL.DataBind();
            }
        }

        public Guid SelectedDepartment
        {
            set
            {
                DepartmentsDDL.ClearSelection();
                DepartmentsDDL.Items.FindByValue(value.ToString()).Selected = true;
            }
            get { return new Guid(DepartmentsDDL.SelectedItem.Value); }
        }

        public IList<UniversalModelDDL> Participants
        {
            set
            {
                ViewState["Participants"] = value;
                ParticipantsGridView.DataSource = value;
                ParticipantsGridView.DataBind();
            }
            get { return (IList<UniversalModelDDL>)ViewState["Participants"]; }
        }

        public IList<ParticipantsModelDDL> ChangedParticipants
        {
            get
            {
                if (ViewState["ChangedParticipants"] == null) return new List<ParticipantsModelDDL>();
                return (IList<ParticipantsModelDDL>)ViewState["ChangedParticipants"];
            }
            set { ViewState["ChangedParticipants"] = value; }
        }

        public int Priority
        {
            set
            {
                PrioritiesDDL.ClearSelection();
                PrioritiesDDL.Items.FindByValue(value.ToString(CultureInfo.InvariantCulture)).Selected = true;
            }
            get { return Int32.Parse(PrioritiesDDL.SelectedItem.Value); }
        }

        public Guid SelectedExecutor
        {
            set
            {
                ExecutorsDDL.ClearSelection();
                ExecutorsDDL.Items.FindByValue(value.ToString()).Selected = true;
            }
            get { return new Guid(ExecutorsDDL.SelectedItem.Value); }
        }

        public string WorkingTime
        {
            set { ViewState["WorkingTime"] = value; }
            get { return (string)ViewState["WorkingTime"]; }
        }

        public string ResultWorkingTime
        {
            set { CurrentTimeLabel.Text = value; }
        }

        public string ExecutorName { get { return (string)ViewState["ExecutorName"]; } set { ViewState["ExecutorName"] = value; } }

        public bool TaskExecutionInProgress
        {
            set
            {
                if (value)
                {
                    StartProcess.Visible = false;
                    PauseProcess.Visible = true;
                }
                else
                {
                    StartProcess.Visible = true;
                    PauseProcess.Visible = false;
                }
            }
        }

        public string TaskName
        {
            set { TaskNameLabel.Text = value; }
            get { return TaskNameEdit.Text; }
        }

        public string Tag
        {
            set { TagTB.Text = value; }
            get { return TagTB.Text; }
        }

        public string TaskOwner { get { return (string)ViewState["TaskOwner"]; } set { ViewState["TaskOwner"] = value; } }

        public Guid TaskID
        {
            set { TaskNumberLabel.Text = value.ToString(); }
            get { return new Guid(Request.QueryString["ID"]); }
        }

        public string TaskStatus
        {
            set { TaskStatusLabel.Text = value; }
        }

        public string DateCreate
        {
            set { DateCreateLabel.Text = value; }
        }

        public string HistoryEntryText
        {
            get { return Editor.Text; }
            set { Editor.Text = value; }
        }

        public string UsersSearchString
        {
            get { return UsersSearchTB.Text; }
        }

        public UniversalModelDDL DeletedParticipant
        {
            get { return deletedParticipant; }
            set { deletedParticipant = value; }
        }

        public DateTime? ExpirationDate
        {
            get { return (DateTime?)dxExpirationDate.Value; }
            set { dxExpirationDate.Value = value; }
        }

        public string RedirectWebPath { get; set; }

        #endregion

        private void DownloadFile(File file)
        {
            var fileName = file.FileName;
            if (Request.Browser.IsBrowser("IE"))
            {
                fileName = HttpUtility.UrlPathEncode(fileName);
                if (fileName != null) fileName = fileName.Replace(@"+", @"%20");
            }
            Response.ContentType = "application/octet-stream";
            Response.HeaderEncoding = Encoding.UTF8;
            Response.ContentEncoding = Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
            Response.BinaryWrite(file.Content);
            Response.End();
        }

        protected void cbVoting_Callback(object sender, CallbackEventArgs e)
        {
            Presenter.OnSetRating();
            Thread.Sleep(1000);
            e.Result = string.Format("{0} {1} {1:0.##}", 0, RatingValue);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TaskExecutionInProgress = false;
            Editor.BasePath = GetBasePath() + TaskKernelConfiguration.EditorPath;
            if (!Page.IsPostBack)
            {
                Presenter.OnViewInitialized();
                if (!String.IsNullOrEmpty(RedirectWebPath))
                {
                    Response.Redirect(RedirectWebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage +
                                      TaskID);
                }
            }
            if (Request.QueryString["FileID"] == null) return;
            var file = Filez.SingleOrDefault(x => x.UID == new Guid(Request.QueryString["FileID"]));
            if (file != null && file.Content != null && file.Content.Length > 0) DownloadFile(file);
        }

        protected void ParticipantSearch_TextChanged(object sender, EventArgs e)
        {
            Presenter.OnSearchParticipant();
        }

        protected void ParticipantsView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            FillDeletedParticipant(e);
            Presenter.OnDelParticipant();
        }

        private void FillDeletedParticipant(GridViewDeleteEventArgs e)
        {
            var IndexOfDeletedParticipant = e.RowIndex;
            const int ColumnWithFullName = 0;
            var row = ParticipantsGridView.Rows[IndexOfDeletedParticipant];
            var id = (Guid)ParticipantsGridView.DataKeys[IndexOfDeletedParticipant].Values["ID"];
            deletedParticipant = new UniversalModelDDL(id, row.Cells[ColumnWithFullName].Text);
        }

        protected void ReminderCB_CheckedChanged(object sender, EventArgs e)
        {
            ReminderPanel.Visible = !ReminderPanel.Visible;
            ReminderNote = "";
            ReminderDate = null;
        }

        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            FilesPanel.Visible = !FilesPanel.Visible;
        }

        protected void HistoryEntriesGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortHistory(e.SortExpression, SortDirection);
            WriteCookies(e);
            SortDirection = !SortDirection;
        }

        private void SortHistory(string sortExpression, bool sortDirection)
        {
            if (sortDirection)
                HistoryEntries = HistoryEntries.AsQueryable().OrderBy(sortExpression).ToList();
            else
                HistoryEntries = HistoryEntries.AsQueryable().OrderByDescending(sortExpression).ToList();
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnDelete();
            Response.Redirect(WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.ArchivePage);
        }

        protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
        {
            Presenter.OnForceClose();
            Response.Redirect(WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.DefaultPage);
        }

        protected void ImageButton1_Click2(object sender, ImageClickEventArgs e)
        {
            ErrorMessage = "";
            Presenter.OnClose();
            if (!string.IsNullOrEmpty(ErrorMessage)) return;
            Response.Redirect(WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.DefaultPage);
        }

        protected void ImageButton1_Click3(object sender, ImageClickEventArgs e)
        {
            Presenter.OnSave();
            if (!String.IsNullOrEmpty(RedirectWebPath))
                Response.Redirect(RedirectWebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage + TaskID);
            else Response.Redirect(WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage + TaskID);
        }

        protected void ImageButton1_Click4(object sender, ImageClickEventArgs e)
        {
            Presenter.OnAddParticipant();
        }

        private void WriteCookies(GridViewSortEventArgs e)
        {
            CookieHelper.WriteCookie("EditPage", e.SortExpression);
            CookieHelper.WriteCookie("EditPage" + "sortDirectionASC", SortDirection.ToString());
        }

        protected void BtnSendContent_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnSentContent();
            Response.Redirect(WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage + TaskID);
        }

        protected void BtnUnArchive_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnUnClose();
            Response.Redirect(WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage + TaskID);
        }

        protected void TaskNameLabel_Click(object sender, EventArgs e)
        {
            TaskNameLabel.Visible = false;
            TaskNameEdit.Text = TaskNameLabel.Text;
            TaskNameEdit.Visible = true;
        }

        protected void CheckBox1_CheckedChanged1(object sender, EventArgs e)
        {
            Presenter.OnRefreshHistory();
        }

        protected void StartProcess_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnStartTaskProcess();
        }

        protected void PauseProcess_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnPauseTaskProcess();
        }
    }
}